﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.SaleOrders;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.SaleOrders;

namespace Reporting.API.Application.CommandHandler.SaleOrders
{
    /// <summary>
    /// 修改 销售订单
    /// </summary>
    public class UpdateSaleOrderCommandHandler : IRequestHandler<UpdateSaleOrderCommand, ApiResult>
    {
        private readonly ISaleOrderRepository _saleOrderRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateSaleOrderCommandHandler> _logger;

        public UpdateSaleOrderCommandHandler(ILogger<UpdateSaleOrderCommandHandler> logger, IMapper mapper, ISaleOrderRepository saleOrderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _saleOrderRepository = saleOrderRepository;
        }

        public async Task<ApiResult> Handle(UpdateSaleOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产计划
                var SaleOrders = await _saleOrderRepository.GetAsync(x => x.SaleOrderID == request.SaleOrderID);

                if (SaleOrders == null)
                {
                    return ApiResult.Fail("修改当前数据不存在", StatusCodeEnum.BadRequest);
                }


                // 更新生产计划
                var UpdateSaleOrder = _mapper.Map(request, SaleOrders);
                await _saleOrderRepository.UpdateAsync(UpdateSaleOrder);

                return ApiResult.Success(StatusCodeEnum.Success);


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "销售订单修改失败");
                throw;
            }
        }
    }
}
